package test.test02.MyThread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    public MyThreadPool(int n){
        for(int i = 0;i < n;i++){
            Thread t = new Thread(()->{
                try{
                    while(true){
                        Runnable task = queue.take();
                        //如果队列中没有任务，take就会阻塞，直到其他线程执行submit为止
                        task.run();                                     
                    }                                       
                }catch(InterruptedException e){
                    e.printStackTrace();                
                }                            
            }); 
            t.start();   
        }
    }
    public void submit(Runnable task)throws InterruptedException{
        queue.put(task);
    }
    public static void main(String[] args) {
        MyThreadPool service = new MyThreadPool(10);
        for(int i = 0;i < 100;i++){
            //变量捕获问题：把i的值转化为事实最终变量id
            int id = i;
            try{
                service.submit(new Runnable(){
                    @Override
                    public void run(){
                        System.out.println("work" + id);       
                    }    
                });
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        } 
    }
}
